package org.example.netty.decoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * 符号分隔解码器
 * @author zhao rui
 */
public class NettyStickyPacketDelimiterBasedFrameServer {

    private static final Logger logger = LogManager.getLogger(NettyStickyPacketDelimiterBasedFrameServer.class);

    // private static final int PING_BYTES_LENGTH = 25;

    private static final int DEFAULT_PORT = 8998;

    private static final String DELIMITER = "\r\n";

    private final int port;

    public NettyStickyPacketDelimiterBasedFrameServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        logger.info("netty server is starting.");

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                protected void initChannel(SocketChannel ch) {
                    ch.pipeline()
                            // 设置了最大帧长度（maxLength），则当帧长度超过这个值时，会抛出异常或进行其他错误处理。
                            .addLast(new DelimiterBasedFrameDecoder(
                                    1024,
                                    Unpooled.copiedBuffer(DELIMITER.getBytes())))
                            .addLast(new StringDecoder())
                            .addLast(new NettyStickyPacketServerHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            logger.info("netty server started, listened[" + port + "].");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        NettyStickyPacketDelimiterBasedFrameServer server = new NettyStickyPacketDelimiterBasedFrameServer(DEFAULT_PORT);
        server.start();
    }

}